package etnorservice.etnor_service.controller;

import etnorservice.etnor_service.aop.annoution.Permission;
import etnorservice.etnor_service.domain.po.SystemLog;
import etnorservice.etnor_service.request.SearchLogRequest;
import etnorservice.etnor_service.result.Result;
import etnorservice.etnor_service.service.LogService;
import etnorservice.etnor_service.service.UserService;
import etnorservice.etnor_service.utils.JwtTokenUtil;
import net.sf.jsqlparser.parser.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: cc
 * @Date: 2024/08/23/8:38
 **/
@RestController
public class LogController {
    @Autowired
    private LogService logService;
    @Autowired
    private UserService userService;

    @GetMapping("/system/logs")
    public Result<SystemLog> getLogs(
            @RequestParam(required = false) String ipAddress,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestHeader(value = "Authorization", required = false)
                    String authorizationHeader

    ) {
        Result result=new Result();
        SearchLogRequest searchLogRequest = new SearchLogRequest();
        String account=
                new JwtTokenUtil().
                        getAccountFromToken(extractTokenFromHeader(authorizationHeader));
        int role=userService.findRoleByAccount(Integer.parseInt(account)).getRole();

        if(role==0) {
            searchLogRequest.setIpAddress(ipAddress.isEmpty() ? null : ipAddress);
            // 将时间字符串转换为时间戳
            if (startTime != null && !startTime.isEmpty()) {
                searchLogRequest.setStartTime(parseTimestamp(startTime));
            }
            if (endTime != null && !endTime.isEmpty()) {
                searchLogRequest.setEndTime(parseTimestamp(endTime));
            }

            searchLogRequest.setOffset((page - 1) * pageSize);
            searchLogRequest.setLimit(pageSize);


            result.setData(logService.findLog(searchLogRequest));
            result.setCode(200);
        }else {
            result.setCode(40001);
            result.setMessage("抱歉，您无该权限！");
        }





        return result;
    }
    private Timestamp parseTimestamp(String timestampStr) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            sdf.setTimeZone(TimeZone.getTimeZone("UTC")); // 设置时区为 UTC
            Date date = sdf.parse(timestampStr);

            // 将日期转换为当天的开始时间
            Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
            calendar.setTime(date);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);

            return new Timestamp(calendar.getTimeInMillis());
        } catch (java.text.ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    private String extractTokenFromHeader(String header) {
        if (header == null || !header.startsWith("Bearer ")) {
            return null;
        }
        return header.substring(7).trim(); // 去除 "Bearer ".length() 后面的空格
    }

    @GetMapping("/system/resource")
    @Permission(value = 0)
    public Result resource(){
        Result result=new Result();




        return result;
    }
    @GetMapping("/logs")
    public Result findUpdateLogs(){
        Result result = new Result();
        result.setData(logService.findUpdateLogs());
        return result;
    }


}
